package mo.tags.breadthfirst;

import mo.common.TreeNode;

import java.util.*;

public class L102 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
        List<List<Integer>> res = new ArrayList<>();
        ArrayDeque<TreeNode> cur = new ArrayDeque<>();
        cur.add(root);

        List<Integer> levels = new ArrayList<>();
        ArrayDeque<TreeNode> children = new ArrayDeque<>();
        while (!cur.isEmpty()) {
            TreeNode node = cur.pollFirst();
            levels.add(node.val);
            if (node.left != null) {
                children.add(node.left);
            }
            if (node.right != null) {
                children.add(node.right);
            }
            if (cur.isEmpty()) {
                cur = children;
                children = new ArrayDeque<>();
                res.add(new ArrayList<>(levels));
                levels.clear();
            }
        }
        return res;
    }

}
